// 简化导航系统 - 全栈Node.js应用

// 页面导航函数
function navigateTo(page) {
    window.location.href = page;
}

// 返回上一页
function goBack() {
    window.history.back();
}

// 刷新当前页面
function refreshPage() {
    window.location.reload();
}

// 检查登录状态并重定向
function checkAuthAndRedirect(targetPage) {
    const token = localStorage.getItem('authToken');
    if (!token) {
        alert('请先登录');
        showLogin();
        return false;
    }
    navigateTo(targetPage);
    return true;
}

// 显示登录模态框
function showLogin() {
    const modal = document.getElementById('loginModal');
    if (modal) {
        modal.style.display = 'block';
    }
}

// 关闭登录模态框
function closeLogin() {
    const modal = document.getElementById('loginModal');
    if (modal) {
        modal.style.display = 'none';
    }
}

// 安全的页面导航（需要登录）
function secureNavigateTo(page) {
    return checkAuthAndRedirect(page);
}

// 初始化页面导航
function initNavigation() {
    // 为所有导航链接添加点击事件
    const navLinks = document.querySelectorAll('[data-nav]');
    navLinks.forEach(link => {
        link.addEventListener('click', function(e) {
            e.preventDefault();
            const target = this.getAttribute('data-nav');
            if (this.getAttribute('data-secure') === 'true') {
                secureNavigateTo(target);
            } else {
                navigateTo(target);
            }
        });
    });

    // 关闭模态框事件
    const closeButtons = document.querySelectorAll('.close');
    closeButtons.forEach(button => {
        button.addEventListener('click', function() {
            this.closest('.modal').style.display = 'none';
        });
    });

    // 点击模态框外部关闭
    const modals = document.querySelectorAll('.modal');
    modals.forEach(modal => {
        modal.addEventListener('click', function(e) {
            if (e.target === this) {
                this.style.display = 'none';
            }
        });
    });

    // 键盘快捷键
    document.addEventListener('keydown', function(e) {
        if (e.altKey) {
            switch(e.key) {
                case '1': navigateTo('dashboard.html'); break;
                case '2': navigateTo('products.html'); break;
                case '3': navigateTo('orders.html'); break;

                case 'h': case 'H': navigateTo('index.html'); break;
            }
        }
    });
}

// 检查系统状态
async function checkSystemStatus() {
    try {
        const response = await fetch('/api/health');
        const data = await response.json();
        
        // 更新状态显示
        const statusElements = {
            'backendStatus': data.status === 'healthy' ? '✓ 运行正常' : '✗ 服务异常',
            'databaseStatus': data.database === 'connected' ? '✓ 已连接' : '✗ 连接失败',
            'redisStatus': data.redis === 'connected' ? '✓ 已连接' : '✗ 连接失败'
        };

        Object.keys(statusElements).forEach(id => {
            const element = document.getElementById(id);
            if (element) {
                const status = statusElements[id];
                const isSuccess = status.startsWith('✓');
                element.innerHTML = `<span class="${isSuccess ? 'status-success' : 'status-error'}">${status}</span>`;
            }
        });
    } catch (error) {
        // 更新所有状态为错误
        ['backendStatus', 'databaseStatus', 'redisStatus'].forEach(id => {
            const element = document.getElementById(id);
            if (element) {
                element.innerHTML = '<span class="status-error">✗ 检查失败</span>';
            }
        });
    }
}

// 检查登录状态
function checkLoginStatus() {
    const token = localStorage.getItem('authToken');
    if (token) {
        // 尝试获取当前用户信息
        API.auth.getCurrentUser()
            .then(response => {
                if (response.success) {
                    const userElement = document.getElementById('currentUser');
                    const loginBtn = document.querySelector('.btn-login');
                    const logoutBtn = document.querySelector('.btn-logout');
                    
                    if (userElement) userElement.textContent = response.data.user.username;
                    if (loginBtn) loginBtn.style.display = 'none';
                    if (logoutBtn) logoutBtn.style.display = 'inline-block';
                }
            })
            .catch(() => {
                // 令牌无效，清除本地存储
                localStorage.removeItem('authToken');
            });
    }
}

// 处理登录
async function handleLogin() {
    const email = document.getElementById('loginEmail')?.value;
    const password = document.getElementById('loginPassword')?.value;

    if (!email || !password) {
        alert('请输入邮箱和密码');
        return;
    }

    try {
        const response = await API.auth.login(email, password);
        if (response.success) {
            alert('登录成功！');
            closeLogin();
            checkLoginStatus();
            // 跳转到仪表盘
            navigateTo('dashboard.html');
        } else {
            alert('登录失败: ' + response.message);
        }
    } catch (error) {
        alert('登录错误: ' + error.message);
    }
}

// 退出登录
function logout() {
    API.auth.logout();
    localStorage.removeItem('authToken');
    
    const userElement = document.getElementById('currentUser');
    const loginBtn = document.querySelector('.btn-login');
    const logoutBtn = document.querySelector('.btn-logout');
    
    if (userElement) userElement.textContent = '未登录';
    if (loginBtn) loginBtn.style.display = 'inline-block';
    if (logoutBtn) logoutBtn.style.display = 'none';
    
    alert('已退出登录');
    navigateTo('index.html');
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    initNavigation();
    checkSystemStatus();
    checkLoginStatus();
    
    // 登录表单提交
    const loginForm = document.getElementById('loginForm');
    if (loginForm) {
        loginForm.addEventListener('submit', function(e) {
            e.preventDefault();
            handleLogin();
        });
    }
});

// 导出函数供全局使用
window.navigateTo = navigateTo;
window.goBack = goBack;
window.refreshPage = refreshPage;
window.secureNavigateTo = secureNavigateTo;
window.showLogin = showLogin;
window.closeLogin = closeLogin;
window.handleLogin = handleLogin;
window.logout = logout;
window.checkSystemStatus = checkSystemStatus;
window.checkLoginStatus = checkLoginStatus;